require './../../../../libs/styles/list.sass'
require './../../../../libs/styles/messagePush.sass'
require 'ng-table-css'
require 'datetimepickerCss'
require 'datetimepickerJs'

module.exports = angular.module 'messagePush.new', [
  require('ng-table').name
  require('dialogService').name
  require('sessionService').name
]
.controller 'MessagePushNewCtrl', ($log, $rootScope,$state,$filter, $scope, $location, $timeout, NgTableParams)->
  $log.log "messagePush new controller init"
  commonService  = $scope.commonService
  messagePushService   = $scope.messagePushService
  options = {}
  args = {}
  $scope.http = true
  $scope.uidList = true
  _config = ->
    $scope.pushObj =
      "info.yihua.manager":"工长APP"
      "info.yihua.master":"装修APP"
    $scope.message =
      "description":""
#      "appointSendTime":"2016-05-12 20:00"
      "pushMode":"now"
      "isGlobal": "true"
      "uidList":[]
      "message":
        "content":""
        "refer": ""
        "appPackage": "info.yihua.manager"
    $scope.select = "category": "disabled": false
    $scope.$watch "message.message.refer", (newVal)->
#      return if !newVal
      $log.log $scope.message.message.referf
      return if !newVal
      reg  = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/
      r = reg.test $scope.message.message.refer
      $log.log r
      $scope.http = r
    ,true

    $scope.$watch "message.uidList", (newVal)->
      $log.log $scope.uidList
      if $scope.message.uidList is ""
        return $scope.uidList = true
      return if !newVal
      reg  = /^\d+(\,\d+)?$/
      r = reg.test $scope.message.uidList
      $log.log r
      $scope.uidList = r
    ,true

  _load = ->
    $scope.messagePushTable = new NgTableParams angular.extend(options, $location.search()), args
  _config()
  _load()

  $scope.timeInput = ()->
    if $scope.message.pushMode == "other"
      $timeout ->
        $("#pushTime").datetimepicker({
          format: 'yyyy-mm-dd hh:ii'
          weekStart: 1
          todayBtn:  1
          autoclose: 1
          todayHighlight: 1
          startView: 2
          forceParse: 0
          showMeridian: 1
          minuteStep: 1
        })
      , 0
  $scope.save = ->
    if $scope.message.pushMode is "now"
      $scope.message.appointSendTime = null
    else
      $scope.message.appointSendTime = $scope.message.pushTime
    $scope.message.refer = null if $scope.message.refer is ""
    $scope.message.uidList = if $scope.message.isGlobal is "true" then null else $scope.message.uidList
    $scope.message.uidList = $scope.message.uidList.split(",") if $scope.message.uidList != null
    messagePushService.new $scope.message,->
      $state.go 'index.messagePush.list'
  $scope.cancel = -> $state.go 'index.messagePush.list'
